package 多线程;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author zhang lei
 * @Date 2021-11-12 14:09
 */
public class Supplier {
    public static void main(String[] args) {
        Supply supply = new Supply();
        new Thread(supply, "小明").start();
        new Thread(supply, "老师").start();
        new Thread(supply, "黄牛").start();
        new Thread(supply, "黄牛2").start();
        new Thread(supply, "黄牛3").start();
        new Thread(supply, "黄牛4").start();

        Seller seller = new Seller(supply);
        new Thread(seller, "小花").start();
        new Thread(seller, "小美").start();
        new Thread(seller, "小力").start();
    }
}

class Supply implements Runnable{

    public int num = 10;

    private Lock lock = new ReentrantLock();


    @Override
    public void run() {
        while (true) {
            lock.lock();
            try {
                while (num<=0) {
                    System.out.println(Thread.currentThread().getName() + "休息200ms");
                    Thread.sleep(200);
                }
                System.out.println(Thread.currentThread().getName()+" 卖出第"+num--+"张票");
                Thread.sleep(1000);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }

    }
}

class Seller implements Runnable{

    private Supply supply;

    private Lock lock = new ReentrantLock();

    public Seller(Supply supply) {
        this.supply = supply;
    }

    @Override
    public void run() {
        while (true) {
            lock.lock();
            try {
                while (supply.num ==10) {
                    System.out.println(Thread.currentThread().getName() + "休息");
                    Thread.sleep(200);
                }
                System.out.println(Thread.currentThread().getName() + "添加第"+supply.num++ +"张票");
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }
}
